﻿using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace JESAI.Common.Util
{
    public class PdfUtility
    {
        /// <summary>
        /// 获取组合后的PDF流
        /// </summary>
        /// <param name="filetype">文件类型</param>
        /// <param name="fileName">文件路径</param>
        /// <returns>返回组合后的PDF流</returns>
        public static MemoryStream GetPDFFiles(List<Dictionary<string, object>> dictList)
        {
            if (dictList == null || dictList.Count == 0) return new MemoryStream();

            using (MemoryStream output = new MemoryStream())
            {
                Document document = new Document();

                PdfWriter pdfwrite = PdfWriter.GetInstance(document, output);
                document.Open();
                foreach (var dict in dictList)
                {
                    var fileType = dict.Keys.Contains("Filetype") ? dict["Filetype"].ToString().ToLower().Trim() : null;
                    var path = dict.Keys.Contains("Path") ? dict["Path"].ToString() : null;
                    var FileData = dict.Keys.Contains("FileData") ? Convert.FromBase64String(Convert.ToString(dict["FileData"])) : null;
                    if (fileType == ".pdf")
                    {
                        MergrePDF(pdfwrite, document, path, FileData);
                    }
                    else if (fileType == ".png" || fileType == ".jpg" || fileType == ".jpeg" || fileType == ".gif" || fileType == ".tiff" || fileType == ".bmp")
                    {
                        ImageConvertToPDF(document, path);
                    }
                }
                document.Close();
                pdfwrite.Close();
                return output;
            }
        }

        public static void MergrePDF(PdfWriter writer, Document document, string filePath, byte[] FileData)
        {
            PdfReader reader = null;
            PdfContentByte contentByte = writer.DirectContent;
            PdfImportedPage importedPage;

            if (string.IsNullOrWhiteSpace(filePath) == false)
            {
                reader = new PdfReader(filePath);
            }
            else if (FileData != null && FileData.Count() > 0)
            {
                reader = new PdfReader(FileData);
            }
            if (reader == null) throw new ArgumentNullException(string.Format("请确保文件路径{0}或文件流{1}不为空", filePath, FileData));

            int iPageNum = reader.NumberOfPages;
            for (int j = 1; j <= iPageNum; j++)
            {
                //将原pdf大小设置为新页大小
                var size = reader.GetPageSize(j);
                document.SetPageSize(size);

                //这个必须要创建新页，否则下面的内容会与第一页重合
                document.NewPage();
                //读取旧的pdf，然后添加到新的pdf 中
                importedPage = writer.GetImportedPage(reader, j);
                //添加到新的pdf中可设置位置
                contentByte.AddTemplate(importedPage, 0, 0);
            }
        }

        public static void ImageConvertToPDF(Document document, string fileName)
        {
            Image jpg = Image.GetInstance(fileName);
            jpg.Alignment = Image.ALIGN_CENTER;
            if (jpg.Width > jpg.Height)
            {
                jpg.Rotation = (float)Math.PI / 2;
            }
            jpg.ScaleToFit(PageSize.A4.Width - 25, PageSize.A4.Height - 50);

            document.NewPage();
            document.Add(jpg);
        }       
    }
}
